2-2

Physicist's Introduction to Mathematica 6

Third Edition 2007

PHYSICS 200

Nicholas Wheeler

Laboratory 2

More Advanced  Graphics

We resume our survey of the graphic resources provided by Mathematica 6 where we left off in Laboratory 1.

Graphics Primitives

Graphics are constructed by assembly of points, lines and similar "primatives." It is sometimes useful to know that those are directly accessible to the user. The following commands provide descriptions of some of the most essential primitive elements (be sure in each case to see where ≫ takes you):

?Point
?Line
?Rectangle
?Circle
?Disk
?Text

I use those primitives to construct a graphic in (if I may be forgiven for trivializing the work of an important artist) the "style of Piet MouseOver" (1872–1944):

Mondrian=Graphics[{
{PointSize[0.05],Point[{.5,.5}]},
{PointSize[0.1],Point[{1,1.5}]},
{RGBColor[0,0,1],PointSize[0.15],Point[{1.2,-.5}]},
Circle[{0,0},1],
{GrayLevel[0.5],Disk[{-.5,.75},.75]},
{RGBColor[1,0,0],Rectangle[{-.25,-.25},{2,.25}]},
{{RGBColor[0,1,0],Rectangle[{1.6,-.6},{1.7,1.25}]},
Text["A Design After Mondrian", {1.7,-1}]}
}];

NOTE the use of a terminal ; to prevent prompt display of the graphic  in question.

Show[Mondrian]

In response to the command InputForm[figure] Mathematica responds by reporting how it went about assembling primitives to produce the figure in question, as the following examples illustrate:

First Example

InputForm[Mondrian]

Second Example

fib=Table[Fibonacci[n],{n,10}];
fibfigure=ListPlot[fib,PlotStyle->PointSize[Large], Ticks->{{2,4,6,8,10},{5,8,13,21,34,55}}, AxesOrigin->{0,0}]

InputForm[fibfigure]

Third Example

sinefigure=Plot[Sin[x],{x,0,2π}, Ticks->{{π,2π},{-1,+1}}]

InputForm[sinefigure]

This fulsome output provides vivid evidence of why people have tended to avoid accurate figures by hand! And why they can never hope to achieve the accurate detail that Mathematica insists upon achieving.

To learn more about this subject, go to Help > Documentation Center and, in the search window, ask first about ref/Graphics and then about tutorial/TheStructureOfGraphics.

The Graphics Menu

New to v.6 are the resouces made available by the Graphics menu.

Consult Help > Documentation Center and, in the search window, ask about guide/GraphicsMenu.

Go first to Graphics > New Graphic (which introduces a rectangular space upon which to draw), then to Graphics > Drawing Tools, which produces a tablet displaying various tools you can  use to construct a graphic very much as you would draw on a piece of paper: Mathematica automatically converts you art into a sequence of primitive graphic commands.

Example

I sketched the following figure

and then Copy/Pasted it into the following definition:

Doodle=;

Show[Doodle]

This, according to Mathematica, is what I did:

InputForm[Doodle]

SUGGESTION: Try similar experiments.

The command

?Arrow

(follow the ≫) provides a specialized variant of the resources made avilable by the Graphics Menu.

Example

Graphics[{Arrowheads[Large],Arrow[{{1,0},{2,1},{3,0},{4,1}}]}]

Graphical Representation of Vector Fields

As physicists, we spend a lot of time thinking about "vector fields" of various sorts (they might be electric/magnetic/gravitational force fields, or might refer to some kind of "flow," etc.)…but we seldom attempt to draw pictures of such objects.  Mathematica takes the pain out of that exercise, and the results are often quite informative.

To gain access to that powerful resource one must import the Vector Field Plotting Package …but, before we do so, I interpolate a general comment concerning

The Preferred Way to Load Packages

Two alternative commands are available, the Needs command

?Needs

and the Get command (of which << is the symbolic name):

?Get

?<<

Mathematica tends to become caught up in an endless loop and crash when asked to "get" something that has already been "got," whereas Needs undertakes to get the thing only if it has not already been got, and thus avoids such difficulties. Needs—not <<—is therefore the preferred (because least hazardous) command.

Returning now to the main line of the present discussion, we import the package

Needs["VectorFieldPlots`"]

and inquire about its contents:

?VectorFieldPlot

Click on the ≫, then on the MORE ABOUT at the bottom of the page and discover that the package supplies several additional commands—most notably

?GradientFieldPlot
?HamiltonianFieldPlot

and their 3D analogs, which are of especial interest to physicists.

Example

A 2-dimensional vector field is a 2-element list, of the form {(Subscript[V, x])[x,y], (Subscript[V, y])[x,y]}. Consider this specific example:

vectorfield[x_,y_]:={(x^4)+(y^4)-6(x^2)(y^2)-1,4x (y^3)-4(x^3)y}

VectorFieldPlot[vectorfield[x,y],{x,0,3},{y,0,3}]

A More Interesting Example: Electric Dipole

The potential in the vicinity of an electric dipole can be described

dipolepotential[x_,y_]:=(1/(Sqrt[.1+(x^2)+(((y-1))^2)]))-(1/(Sqrt[.1+(x^2)+(((y+1))^2)]))

REMARK: The blue terms on the right have been introduced (by me,  by hand) to temper the singularities which occur at the positions of the ± charges.

equipotentials=ContourPlot[dipolepotential[x,y],{x,-4,4},{y,-6,6}, AspectRatio->Automatic]

REMARK: The AspectRatio -> Automatic has been introduced to keep the figure from becoming deceptively squashed in the y-direction. Execute the command with that detail omitted and see what you get.

The electric field (a vector field) is the negative gradient of the potential, and has the form shown below:

dipolefield=GradientFieldPlot[-dipolepotential[x,y],{x,-4,4},{y,-6,6}, 
AspectRatio->Automatic]

It is instructive to superimpose the two preceding figures:

Show[equipotentials, dipolefield]

Example: 3-Dimensional Gradient Field

Scalarfield[x_,y_,z_]:=(x^2)y-z

AssciatedVectorField=GradientFieldPlot3D[Scalarfield[x,y,z],{x,0,1},{y,0,1},{z,0,1}]

AssciatedVectorField=GradientFieldPlot3D[Scalarfield[x,y,z],{x,0,1},{y,0,1},{z,0,1}, VectorHeads->True]

Use the mouse to view this figure from various angles.

Look now to what in some contexts would be called "equipotential surfaces":

SurfacesOfConstantValue=ContourPlot3D[Scalarfield[x,y,z],{x,0,1},{y,0,1},{z,0,1},ContourStyle->Directive[Orange,Opacity[0.8],Specularity[White,30]] ]

Here we superimpose the preceding figures:

Show[AssciatedVectorField,SurfacesOfConstantValue]

It is evident—most vividly evident if you view the composite figure from the appropriate angle—that the magnitudes of the gradient vectors are indicated not by the length of the arrows (all have the same length) but by the relative sizes of their arrowheads.

Polyhedra

Mathematica 5.2 was supplemented by standard packages—called Graphics`Shapes` and Graphics`Polyhedra`—that provided images and other information about a variety of 3D geometrical forms.  In Mathematica 6 the information formerly available Graphics`Shapes` in has been dispersed to a variety of other sources: in the Documentation Center search for Compatibility/tutorial/Graphics/Shapes to learn about those, which include Torus, MobiusStrip, DoubleHelix and such like.  But the information formerly provided in Graphics`Polyhedra` has in v.6 been written directly into the Kernel. Here I can only hint at the richness of that resource, which I have on occasion found to be quite useful: for further information, return to the Documentation Center and search for ref/PolyhedronData.

PolyhedronData["Dodecahedron"]

View the figure from various angles.

The following commands provide various kinds of information about (in this instance) the dodecahedron:

PolyhedronData["Dodecahedron", "VertexCount"]
PolyhedronData["Dodecahedron", "EdgeCount"]
PolyhedronData["Dodecahedron", "FaceCount"]

PolyhedronData["Dodecahedron", "VertexCoordinates"]

The output here has been a list of 20 3-vectors. Here are the numerical values of their coordinates:

N[%]

Here I use

?ListPointPlot3D

(which I previously declined to discuss, on the ground that it was "seldom useful") to construct a graphic display of that data:

ListPointPlot3D[PolyhedronData["Dodecahedron", "VertexCoordinates"], AspectRatio->Automatic, PlotStyle->PointSize[0.03],BoxRatios->{1,1,1}, Ticks->False]

View the figure from a variety of angles!

If any doubt remains concerning the richness of this resouce, consider the following tiny sampling of the possibilities:

PolyhedronData["Platonic"]
PolyhedronData["Archimedean"]

PolyhedronData["Icosidodecahedron"]

PolyhedronData["GreatRhombicuboctahedron"]

PolyhedronData["GyroelongatedPentagonalBicupola"]

PolyhedronData["SmallStellatedDodecahedron"]

This final command takes a bit longer to run: you might collect paper and scissors while waiting.

GraphicsGrid[Partition[Graphics[Tooltip[PolyhedronData[#,"NetImage"][[1]],PolyhedronData[#,"Name"]]]&/@PolyhedronData["NetImage","Defined"],10]]

For a large collection of design-it-yourself rotatable polyhedra, visit MouseOver.

Composite Figures

Frequently one has need to display related figures in a way that facilitates their comparison.  I review here some some techniques standard to printed publication, my main objective being to prepare the ground for discussion of a much more vividly powerful technique that was made possible by the invention of electronic modes of publication.

Some of the relevant commands employed in this connection by Mathematica 6 differ from those used in earlier versions of Mathematica. Most notably, GraphicsArray has been superseded by GraphicsGrid and Grid.  To read about the details, go to the Documentation Center and search for tutorial/RedrawingAndCombiningPlots.

We begin by introducing a population of functions that acquire importance for physicists because they describe the "eigenstates" of a quantum oscillator:

He[n_,x_]:=(1/(Sqrt[(2^n)]))HermiteH[n,x/(Sqrt[2])]
Ψ[n_,x_]:=(1/(Sqrt[n!(Sqrt[2π])]))(E^(-(1/4)(x^2)))He[n,x]

From such evidence as this

(∫_(-∞)^∞)Ψ[0,x]Ψ[0,x]\[DifferentialD]x
(∫_(-∞)^∞)Ψ[1,x]Ψ[1,x]\[DifferentialD]x
(∫_(-∞)^∞)Ψ[0,x]Ψ[1,x]\[DifferentialD]x

we infer that the Ψ-functions are orthonormal. A few Ψ-functions of low order are plotted below:

state1=Plot[Ψ[0,x],{x,-10,10}, PlotRange->{-0.7,0.7}]
state2=Plot[Ψ[1,x],{x,-10,10}, PlotRange->{-0.7,0.7}]
state3=Plot[Ψ[2,x],{x,-10,10}, PlotRange->{-0.7,0.7}]
state4=Plot[Ψ[3,x],{x,-10,10}, PlotRange->{-0.7,0.7}]
state5=Plot[Ψ[4,x],{x,-10,10}, PlotRange->{-0.7,0.7}]
state6=Plot[Ψ[5,x],{x,-10,10}, PlotRange->{-0.7,0.7}]

We know how to superimpose such figures, since we have already done it a few times:

Show[state1,state2,state3]

Here we assemble them into an array (three side-by-side pairs of figures):

statesarray=Show[GraphicsGrid[{{state1, state2},{state3,state4},{state5, state6}}]]

Here we "box" the preceding figure:

GraphicsGrid[{{state1, state2},{state3,state4},{state5, state6}}, Frame->True, Ticks->None]

The display looks crowded. We can use Spacings

?Spacings

to give the individual figures a bit of breathing room

boxedarray=GraphicsGrid[{{state1, state2},{state3,state4},{state5, state6}}, Frame->True, Ticks->None, Spacings->{Scaled[.2],Scaled[.3]}]

and we can achieve a still better effect by removing the distracting ticks:

newstate1=Show[state1,Ticks->False];
newstate2=Show[state2,Ticks->False];
newstate3=Show[state3,Ticks->False];
newstate4=Show[state4,Ticks->False];
newstate5=Show[state5,Ticks->False];
newstate6=Show[state6,Ticks->False];

finalfigure=GraphicsGrid[{{newstate1, newstate2},{newstate3,newstate4},{newstate5, newstate6}}, Frame->True, Ticks->None, Spacings->{Scaled[.2],Scaled[.3]}]

Here is a different arrangement of the same information:

GraphicsGrid[{{newstate1, newstate2,newstate3},{newstate4,newstate5, newstate6}}, Frame->True, Ticks->None, Spacings->{Scaled[.2],Scaled[.3]}]

Dynamic Display

This is an area in which Mathematica 6 differs most markedly from earlier versions, as becomes evident from the presence of a Dynamic Interactivity box on the Documentation Center page,  and when you click on  the Dynamic Visualization link.

Manipulate

An alternative way to make such comparisons (on-screen, not in print!) is provided by the powerful Manipulate command, which is a new feature of Mathematica 6. For details, enter the following command

?Manipulate

follow the » to where it leads, and (see Tutorials at the bottom of the page) click on Introduction to Manipulate.

Manipulate[Plot[Ψ[n,x],{x,-10,10}, PlotRange->{-0.7,0.7}],{n,0,6,1}]

Move the slide control (which has been set up to control the value of the integer n) to snap through the set of figures that show oscillator states of ascending order.

In the preceding figure the control parameter n ranged in discrete unit steps, from 0 to 6. In the following figure a pair of adjustable parameters range continuously:

Manipulate[Plot[Sin[a x+b],{x,0,2π}, Ticks->{{0,π,2π},{-1,1}}],{a,1,4},{b,0,2π}]

Example: Potential of an Electric Dipole with Adjustable Charges

I reproduce one of the Neat Examples that can be found in the Manipulate notebook, cited above:

Manipulate[ContourPlot[q1/Norm[{x,y}-p[[1]]]+q2/Norm[{x,y}-p[[2]]],{x,-2,2},{y,-2,2},Contours->10],{{q1,-1},-3,3},{{q2,1},-3,3},{{p,{{-1,0},{1,0}}},{-1,-1},{1,1},Locator},Deployed->True]

Manipulate is based upon a more fundamental resource—also new in Mathematica 6—that is described in tutorial/IntroductionToDynamic, and that pemits one to, in effect, "put knobs one equations."

Example

Enter the command, then slide the knob:

{Slider[Dynamic[n],{1,10,1}],Dynamic[Expand[(((a+b))^n)]]}

Example

{DynamicModule[{x=.5},{Slider[Dynamic[x]],Dynamic[Plot[Sin[10y x],{y,0,2Pi}]]}],
DynamicModule[{x=.5},{Slider[Dynamic[x]],Dynamic[Plot[Tan[10y x],{y,0,2Pi}]]}]}

Example: Effects Achieved by the RGBColor[ ] Command

Manipulate[Show[Graphics[{RGBColor[R,G,B],Disk[{0,0},1]},AspectRatio->Automatic]],{R,0,1},{G,0,1},{B,0,1}]

INSTRUCTIONS: Hit all three of the + buttons, then twiddle experimentally with the three slide controls. The "color coordinates" that, when inserted into RGBColor[R,G,B]  would command production of the color on display, can be read from the display windows under the respective slide controls. Given below is a variant of the same idea:

Manipulate[Show[Graphics[{{Opacity[0.5],RGBColor[r,g,b],Disk[{0,0},3/2]},{Opacity[0.5],RGBColor[x,y,z],Disk[{1,0},3/2]}},AspectRatio->Automatic]],{r,0,1},{g,0,1},{b,0,1},{x,0,1},{y,0,1},{z,0,1}]

Animation

Another way to display how a figure moves/morphs when a variable or control parameter is made to range through its (usually continuous) set of allowed values is provided by the animation technique. To achieve animation, one asks Mathematica to use its own good sense to construct a parameterized list of figures, and then to flick through the list. The means of accomplishing such a goal differ in Mathematica 6 from those employed in earlier versions of the software, the net effect of those modifications being that animations are now very easy to construct. To read about them, command

?Animate

and follow the ».

Example: Motion of a Quantum Oscillator

By way of physical motivation: Suppose a quantum oscillator is initially in the equi-weighted superposition of the energy eigenstates  Ψ[m, x] and  Ψ[n, x]:

ψ[x,0]=((Ψ[m,x]+Ψ[n,x])/(Sqrt[2]))

At time t it will be then in the state

ψ[x_,t_]=((Ψ[m,x](E^(-I(m+(1/2))t))+Ψ[n,x](E^(-I(n+(1/2))t)))/(Sqrt[2]))

The probability of finding the particle in the neighborhood of the point x at time t is given then by

P[x,t]=Conjugate[ψ[x,t]]ψ[x,t]=(1/2) ((Ψ[m,x])^2)+Ψ[m,x] Ψ[n,x] Cos[(m-n) t]+(1/2) ((Ψ[n,x])^2)

Notice that t survives only in the cross-term: quantum motion (therefore all motion) is an interference effect! We look to the case m=2 and n=3:

The red part of the following command plots P[x,t] at time t, and the remainder of the command increments t, thus generating the animation:

Animate[Plot[(1/2) ((Ψ[2,x])^2)+Ψ[2,x] Ψ[3,x] Cos[t]+(1/2) ((Ψ[3,x])^2),{x,-10,10},
PlotRange->{0,0.5},
Ticks->None],{t,0,2π}, AnimationRunning->False]

Stop the animation, do repeated clicks on the up-control to accelerate the film, repeated clicks on the down-control to slow it down.

REMARK: The presence of the AnimationRunning->False command causes the animation to run only when when we hit the "Play" button. In the absence of that option, the figure would run all the time, which can become annoying.

Example: Motion of a Classical Oscillator

Here I use graphics primatives to construct the image of a particle oscillating with unit period at the end of a rubber band.

Animate[Show[Graphics[{
{RGBColor[0,0,1],Disk[{2+Cos[2π t],0},.1]},(*mass point*)
{GrayLevel[0.7],Rectangle[{-.1,-.5},{0,.5}]},(*left wall*)
{GrayLevel[0.7],Rectangle[{4,-.5},{4.1,.5}]},(*right wall*)
{RGBColor[1,0,0],Rectangle[{0,-.02+.01Cos[2π t]},{1.9+Cos[2π t],.02-.01Cos[2π t]}]}(*rubber band*)
}],AspectRatio->Automatic],{t,0,1}, AnimationRunning->False]

Note that (and how) the rubber band has been designed to get thicker as it gets shorter. The right wall was included as a way of forcing all frames to be drawn to the same scale; otherwise Mathematica would draw each to its own scale—the scale that Mathematica, in its wisdom, considers in each instance to be "optimal."

More important: notice again the method used to insert comments into the command. In long/complicated commands such comments are often helpful.

Example: 3D Animation

Animate[Plot3D[Sin[x*y+Sin[2π t]], {x,0,3},{y,0,3},Axes->None, PlotPoints->20],{t,0,1}, AnimationRunning->False]

To view the action from a different angle, stop the action, adjust the action, reactivate.

Audio

Mathematica treats graphics and sound as siblings, though the former leads a very busy life while the latter is often neglected. They are controled by quite similar commands. For detailed information about Mathematica 6's audio capabilities, command

?Sound

and follow the ».

Example: Concert A

The function Sin[2 π 440 t]—with t interpreted to mean "time," in  seconds—describes oscillations of unit amplitude at 440 Hz. Here we listen to that function:

Play[Sin[2π 440 t], {t,0,3}]

Hit the Play button to hear a 3-second sample of the tone you have produced.

Beats

Play[Sin[2π 440 t]+Sin[2π 441.5 t], {t,0,3}]

Twang

Play[Sin[2π 440 t](E^(-(t/0.2))), {t,0,3}]

A Non-acoustic Application of Audio

We "listen" to the function that describes (among other things) quantum state of a uniformly accelerated particle:

Plot[AiryAi[-10(x-1)],{x,0,5}]

Play[AiryAi[-100(x-.1)],{x,0,5}]

The following examples are borrowed from the collection that are provided by the command

?Play

Another Such Example: Sound of trhe Riemann Zeta Function

Play[RiemannSiegelZ[1000t],{t,0,4}]

Example: Five Simultaneous Pure Tones with Incommensurate Frequencies

Play[Sum[Sin[1000 Sqrt[n] t],{n,5}],{t,0,4}]

Example: Five Simultaneous Pure Tones with Changing Frequencies

Play[Sum[Sin[2000 2^t n t],{n,5}],{t,0,4}]

Mathematica possesses also some specifically musical audio capabilities. These can be read about by searching for Music/tutorial/Music, and are accessed by importing a Standard Package:

Needs["Music`"]

Just=MusicScale[JustMajor,256,5]
Tempered=MusicScale[TemperedMajor,256,5]
MusicScale[PythagoreanMajor,256,5]

I must admit: the graphic (as oppposed to acoustic) output from audio commands was much more interesting and informative in Mathematica 5 than they have become in Mathematica 6.